from openai import OpenAI
from django.conf import settings

OPENAI_API_KEY = settings.OPENAI_SETTINGS['OPENAI_API_KEY']
OPENAI_BASE_URL = settings.OPENAI_SETTINGS['OPENAI_BASE_URL']
OPENAI_MESSAGE_BACKGROUND = '你可以根据用户提供的CPU,主板,内存,显卡,硬盘,电源,机箱等信息，给出最适合该用户的建议'


class GPT3:
    """
    This class is used to interact with GPT-3 API.
    This Type Includes text,stream,interact
    """

    def __init__(self, background=OPENAI_MESSAGE_BACKGROUND):

        self.background = background
        self.messages = [
            {"role": "system",
             "content": background},
        ]
        client = OpenAI(
            api_key=OPENAI_API_KEY,
            base_url=OPENAI_BASE_URL
        )
        self.client = client
        pass

    def ask_question(self, question):
        self.messages.append({"role": "user", "content": question})
        stream = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=self.messages,
            stream=True
        )
        res = ""
        for chunk in stream:
            if not chunk.choices or chunk.choices[0].delta.content is None:
                continue

            # print(chunk.choices[0].delta.content,end="")
            res += chunk.choices[0].delta.content
        return res

    def ask_question_interactive(self, question):
        self.messages.append({"role": "user", "content": question})
        while True:
            response = self.client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=self.messages,
                temperature=0.7,
            )
            print(response.choices[0].message.content)
            self.messages.append({"role": "assistant", "content": response.choices[0].message.content})
            self.messages.append({"role": "user", "content": input("> ")})

    # def ask_question_by_url(self, question):
    #     self.messages.append({"role": "user", "content": question})
    #     import requests
    #     import json
    #     headers = {"Content-Type": "application/json"}
    #     data = self.messages
    #     response = requests.get('https://api.openai.com/', headers=headers, data=json.dumps(data))
    #     return (response.text)  # 打印响应内容
